from io import BytesIO
import zipfile
import os
import uuid
from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from reportservice.helpers import ApiResponse
import json
import time
from datetime import datetime
from oss_service.views import bucket
from dingtalk_service.yida_client_zhongxin import YidaClient
import requests
import qrcode
from reportlab.pdfgen import canvas
from PyPDF2 import PdfWriter, PdfReader
from reportlab.lib.utils import ImageReader

admin_user_id = "301546025724261514"
base_path = os.path.join(settings.BASE_DIR, r'data')

# 生成二维码图片


def genQrCode(qr_text):
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    qr.add_data(qr_text)  # 这里填写你想转换成二维码的文本
    qr.make(fit=True)
    img = qr.make_image(fill_color="black", back_color="white")
    tmp_url = rf"{base_path}/xiaming_tmp/tmp_img/{int(time.time())}.png"
    img.save(tmp_url)
    return tmp_url


@csrf_exempt
@require_http_methods(["POST"])
def extend_qrcode(request):
    datasource: dict[str, any] = json.loads(request.body)
    qr_x = datasource['qr_x']
    qr_y = datasource['qr_y']
    qr_size = datasource['qr_size']
    proc_ins_id = datasource["procInsId"]
    qr_code = f"https://nb93bf.aliwork.com/o/report-detail?processInstanceId={proc_ins_id}"
    file_url = datasource["fileUrl"]
    full_download_url = YidaClient.get_full_download_url(
        user_id=admin_user_id, download_url=file_url, base_url=r"https://nb93bf.aliwork.com")
    response = requests.get(full_download_url.body.result)
    if response.status_code == 200:
        pdf_content = BytesIO(response.content)
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(qr_code)
        qr.make(fit=True)
        img = qr.make_image(fill_color="black", back_color="white")

        qr_io = BytesIO()
        img.save(qr_io, format="PNG")
        qr_io.seek(0)  # 移动到流的开头
        packet = BytesIO()
        c = canvas.Canvas(packet)
        qr_image = ImageReader(qr_io)
        c.drawImage(qr_image, qr_x, qr_y, qr_size, qr_size)
        c.save()
        packet.seek(0)
        reprt_pdf = PdfReader(pdf_content)
        qr_pdf = PdfReader(packet)
        output = PdfWriter()
        page = reprt_pdf.pages[0]
        page.merge_page(qr_pdf.pages[0])
        output.add_page(page)
        for i in range(1, len(reprt_pdf.pages)):
            output.add_page(reprt_pdf.pages[i])
        pdf_in_memory = BytesIO()
        output.write(pdf_in_memory)
        report_oss_path = f"customer/{datetime.now().strftime('%Y%m')}/{proc_ins_id}/report_with_qr.zip"
        # 创建一个新的 BytesIO 对象用于存储 ZIP 文件
        zip_bytes_io = BytesIO()
        with zipfile.ZipFile(zip_bytes_io, 'w', zipfile.ZIP_DEFLATED) as zip_file:
            pdf_in_memory.seek(0)
            zip_file.writestr('report_with_qr.pdf', pdf_in_memory.read())
            qr_io.seek(0)
            zip_file.writestr('qrcode.png', qr_io.read())
        zip_bytes_io.seek(0)
        bucket.put_object(report_oss_path, zip_bytes_io)
        result = {
            "report": bucket.sign_url('GET', report_oss_path, 3600),
        }
        return ApiResponse.success(result)
    return ApiResponse.fail("二维码生成失败")

# 中信-


@csrf_exempt
@require_http_methods(['GET'])
def getFormData_byProcessInstanceId(request):
    processInstanceId = request.GET.get('processInstanceId')
    userId = request.GET.get('userId')
    print(processInstanceId)
    # 确保 res1 和 res2 都被提供了
    if processInstanceId is None:
        return JsonResponse({'status': 'error', 'message': '缺少必要的参数'})
    # 调用 YidaClient 的方法
    try:
        data = YidaClient.get_process_instance_by_id(processInstanceId, userId)
        if data:
            return ApiResponse.success(data, '表单数据获取成功')
        else:
            return ApiResponse.fail("请求失败，请重试")
        # return JsonResponse({'status': 'success', 'message': '表单数据获取成功', 'data':data})
    except Exception as e:
        print('-----异常-----')
        print(e)
        # 如果有异常，返回错误信息
        return JsonResponse({'status': 'error', 'message': str(e)})
